<?php 
/**
 * SocialEngine
 *
 * @category   Application_Extensions 
 * @package    Suggestion
 * @copyright  Copyright 2009-2010 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Api.php (var) 2010-08-17 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */

class Seaocore_Api_Linkedin_Api { 
  
  
   /**
	 *  Retrive the contacts from the xml response from linkedin server.
	 * 
	 */  
public function retriveContacts ($OBJ_linkedin) {
  
  $response = $OBJ_linkedin->connections('~/connections:(id,first-name,last-name,picture-url)?start=0&count=' . CONNECTION_COUNT);
  if($response['success'] === TRUE) { 
     $connections = new SimpleXMLElement($response['linkedin']); 
     
     if((int)$connections['total'] > 0) {
        $contactInfo = array ();
        $key = 0;
        foreach($connections->person as $connection) { 
           $contactInfo[$key]['name'] = $connection->{'first-name'} . ' ' . $connection->{'last-name'} ;
           $contactInfo[$key]['id'] = (string)$connection->{'id'};
           $contactInfo[$key]['picture'] = (string)$connection->{'picture-url'};
           $key++;
        }
       
        $contactInfo = $this->parseUserContacts ($contactInfo);
     }
     
   }
   else {
     echo "Error retrieving connections:<br /><br />RESPONSE:<br /><br /><pre>" . print_r($response) . "</pre>";die;
   }
  return $contactInfo;
}
  
  
  
  /**
	 *  Parse the contacts in two parts :
	 * 
	 * 1) Contacts which are already at site
	 * 
	 * 2) Contacts which are not on this site
	 * 
	 */  
public function parseUserContacts ($contactInfo) {
  
  $viewer =  Engine_Api::_()->user()->getViewer();
	$user_id = $viewer->getIdentity();
	$table_user = Engine_Api::_()->getitemtable('user');
	$tableName_user = $table_user->info('name');
	
	$inviteTable = Engine_Api::_()->getDbtable('invites', 'invite');
  $inviteTableName = $inviteTable->info('name');
  
	$table_user_memberships = Engine_Api::_()->getDbtable('membership' , 'user');
	$tableName_user_memberships = $table_user_memberships->info('name');
	$SiteNonSiteFriends[] = '';
	
	foreach ($contactInfo as $values) {

		//FIRST WE WILL FIND IF THIS USER IS SITE MEMBER
		$select = $table_user->select()
		->setIntegrityCheck(false)
		->from($tableName_user, array('user_id', 'displayname', 'photo_id'))
		->join($inviteTableName, "$inviteTableName.new_user_id = $tableName_user.user_id", null)
		->where($inviteTableName . '.new_user_id <>?', 0)
		->limit(1)
		->where($inviteTableName . '.social_profileid = ?', $values['id']);

		$is_site_members = $table_user->fetchRow($select);
    if (empty($user_id)) {
			if (!empty($is_site_members->user_id)) {
				continue;
      }

    }
		//NOW IF THIS USER IS SITE MEMBER THEN WE WILL FIND IF HE IS FRINED OF THE OWNER.
		if (!empty($is_site_members->user_id) && $is_site_members->user_id != $user_id) {
			$contact =  Engine_Api::_()->user()->getUser($is_site_members->user_id);
			// check that user has not blocked the member
			if(!$viewer->isBlocked($contact)) {
				// The contact should not be my friend, and neither of us should have sent a friend request to the other.
				$select = $table_user_memberships->select()
				->setIntegrityCheck(false)
				->from($tableName_user_memberships, array('user_id'))
				->where($tableName_user_memberships . '.resource_id = ' . $user_id .' AND ' . $tableName_user_memberships . '.user_id = ' . $is_site_members->user_id )
				->orwhere($tableName_user_memberships . '.resource_id = ' . $is_site_members->user_id .' AND ' . $tableName_user_memberships . '.user_id = ' .$user_id );
				$already_friend = $table_user->fetchRow($select);
				
				//IF THIS QUERY RETURNS EMPTY RESULT MEANS THIS USER IS SITE MEMBER BUT NOT FRIEND OF CURRENTLY LOGGEDIN USER SO WE WILL SEND HIM TO FRIENDSHIP REQUEST.
				if (empty($already_friend->user_id)) { 
					$SiteNonSiteFriends[0][] = $is_site_members->toArray();
				}
			}
		}
		//IF USER IS NOT SITE MEMBER .
		else if (empty($is_site_members->user_id)) {
		  
			$SiteNonSiteFriends[1][] = $values;
		}
	}
	
	$result[0] = '';
	$result[1] = '';
	if (!empty($SiteNonSiteFriends[1]))
	   $result[1] = array_map("unserialize", array_unique(array_map("serialize", $SiteNonSiteFriends[1])));

	if (!empty($SiteNonSiteFriends[0]))    
	   $result[0] = array_map("unserialize", array_unique(array_map("serialize", $SiteNonSiteFriends[0])));
  return $result;
  
   
}

public function sendInvite ($friendsToJoin, $user_data = null) { 
  $viewer = Engine_Api::_()->user()->getViewer();
  if (!$viewer->getIdentity()) {
   $viewer = $user_data; 
  } 
  //Now make the body of invite messge:
  $callbackURL = ( _ENGINE_SSL ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getBaseUrl(). '/seaocore/auth/social-Signup/?type=linkedin&refuser=' . $viewer->getIdentity();
  
  //MAKING THE BODY TEMPLATE:
  
  
  // Verify mail template type
  $mailTemplateTable = Engine_Api::_()->getDbtable('MailTemplates', 'core');
  $mailTemplate = $mailTemplateTable->fetchRow($mailTemplateTable->select()->where('type = ?', 'invite'));
  if( null === $mailTemplate ) {
    return;
  }
 
  $translate = Zend_Registry::get('Zend_Translate');

  $message = $translate->_(Engine_Api::_()->getApi('settings', 'core')->invite_message);
  $message = trim($message);
  $mailParams = array(
                'host' => $_SERVER['HTTP_HOST'],
                'date' => time(),
                'sender_email' => $viewer->email,
                'sender_title' => $viewer->getTitle(),
                'sender_link' => $viewer->getHref(),
                'sender_photo' => $viewer->getPhotoUrl('thumb.icon'),
                'message' => $message,
                'object_link' => $callbackURL,
                
 );
  
  
  // Build subject/body
    

    $subjectKey = strtoupper('_EMAIL_' . $mailTemplate->type . '_SUBJECT');
    $bodyTextKey = strtoupper('_EMAIL_' . $mailTemplate->type . '_BODY');
    $bodyHtmlKey = strtoupper('_EMAIL_' . $mailTemplate->type . '_BODYHTML');
    
    // Detect language
    $recipientLanguage = $translate->getLocale();
    
    if( !Zend_Locale::isLocale($recipientLanguage) ||
        $recipientLanguage == 'auto' ||
        !in_array($recipientLanguage, $translate->getList()) ) {
      $recipientLanguage = $translate->getLocale();
    }
    
    // Get subject and body
      $subjectTemplate  = (string) $translate->_($subjectKey,  $recipientLanguage);
      $bodyTextTemplate = (string) $translate->_($bodyTextKey, $recipientLanguage);
      $bodyHtmlTemplate = (string) $translate->_($bodyHtmlKey, $recipientLanguage);
    $isMember = false;
   // Get headers and footers
  $headerPrefix = '_EMAIL_HEADER_' . ( $isMember ? 'MEMBER_' : '' );
  $footerPrefix = '_EMAIL_FOOTER_' . ( $isMember ? 'MEMBER_' : '' );     
  
  $subjectHeader  = (string) $translate->_($headerPrefix . 'SUBJECT',   $recipientLanguage);
  $subjectFooter  = (string) $translate->_($footerPrefix . 'SUBJECT',   $recipientLanguage);
  $bodyTextHeader = (string) $translate->_($headerPrefix . 'BODY',      $recipientLanguage);
  $bodyTextFooter = (string) $translate->_($footerPrefix . 'BODY',      $recipientLanguage);
  $bodyHtmlHeader = (string) $translate->_($headerPrefix . 'BODYHTML',  $recipientLanguage);
  $bodyHtmlFooter = (string) $translate->_($footerPrefix . 'BODYHTML',  $recipientLanguage);
  
  // Do replacements
  foreach( $mailParams as $var => $val ) {
    $raw = trim($var, '[]');
    $var = '[' . $var . ']';
    //if( !$val ) {
    //  $val = $var;
    //}
    // Fix nbsp
    $val = str_replace('&amp;nbsp;', ' ', $val);
    $val = str_replace('&nbsp;', ' ', $val);
    // Replace
    $subjectTemplate  = str_replace($var, $val, $subjectTemplate);
    $bodyTextTemplate = str_replace($var, $val, $bodyTextTemplate);
    $bodyHtmlTemplate = str_replace($var, $val, $bodyHtmlTemplate);
    $subjectHeader    = str_replace($var, $val, $subjectHeader);
    $subjectFooter    = str_replace($var, $val, $subjectFooter);
    $bodyTextHeader   = str_replace($var, $val, $bodyTextHeader);
    $bodyTextFooter   = str_replace($var, $val, $bodyTextFooter);
    $bodyHtmlHeader   = str_replace($var, $val, $bodyHtmlHeader);
    $bodyHtmlFooter   = str_replace($var, $val, $bodyHtmlFooter);
  }

  // Do header/footer replacements
  $subjectTemplate  = str_replace('[header]', $subjectHeader, $subjectTemplate);
  $subjectTemplate  = str_replace('[footer]', $subjectFooter, $subjectTemplate);
  $bodyTextTemplate = str_replace('[header]', $bodyTextHeader, $bodyTextTemplate);
  $bodyTextTemplate = str_replace('[footer]', $bodyTextFooter, $bodyTextTemplate);
  $bodyHtmlTemplate = str_replace('[header]', $bodyHtmlHeader, $bodyHtmlTemplate);
  $bodyHtmlTemplate = str_replace('[footer]', $bodyHtmlFooter, $bodyHtmlTemplate);

  // Check for missing text or html
  if( !$bodyHtmlTemplate ) {
    $bodyHtmlTemplate = nl2br($bodyTextTemplate);
  } else if( !$bodyTextTemplate ) {
    $bodyTextTemplate = strip_tags($bodyHtmlTemplate);
  }
  
  $API_CONFIG = array(
    'appKey'       => Engine_Api::_()->getApi('settings', 'core')->getSetting('linkedin.apikey'),
	  'appSecret'    =>  Engine_Api::_()->getApi('settings', 'core')->getSetting('linkedin.secretkey'),
	  'callbackUrl'  => null
  );
  
	$OBJ_linkedin = new Seaocore_Api_Linkedin_Linkedin($API_CONFIG);
  $OBJ_linkedin->setTokenAccess($_SESSION['oauth']['linkedin']['access']);
  $response =  $OBJ_linkedin->message($friendsToJoin, $subjectTemplate, $bodyTextTemplate, FALSE);
  if($response['success'] === TRUE) {
    // message has been sent
    //saving the users info in database.
    Seaocore_Api_Facebook_Facebookinvite::seacoreInvite($friendsToJoin, 'linkedin', $viewer);
  }
  
}
  
  
}